<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="消息类型" style="width: 200px" prop="messageType">
        <el-select v-model="queryParams.messageType" placeholder="请选择消息类型" clearable>
          <el-option
            v-for="dict in message_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="状态" style="width: 150px" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态(0:未读 1:已读)" clearable>
          <el-option
            v-for="dict in message_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="top-operation-bar">
      <!-- 状态按钮 -->
       <div class="status-buttons">
        <el-button
          v-for="dict in message_status"
          :key="dict.value"
          :class="{
            'active': queryParams.status === dict.value,
            'default-btn': queryParams.status !== dict.value
          }"
          @click="handleStatusChange(dict.value)"
        >
          {{ dict.label }}
        </el-button>
       </div>
      <div class="operation-container">
        <el-row :gutter="10" class="mb8" justify="end">
          <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['le:message:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleRead"
            v-hasPermi="['le:message:edit']"
          >已读</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleYiduAll"
          v-hasPermi="['le:message:add']"
          >全部已读</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleDeleteAll"
            v-hasPermi="['le:message:export']"
          >全部删除</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      </div>
    </div>
          
    

    <el-table v-loading="loading" :data="messageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="消息内容" align="center" prop="content" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="消息类型" align="center" prop="messageType">
        <template #default="scope">
          <dict-tag :options="message_type" :value="scope.row.messageType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['le:message:edit']">修改</el-button> -->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['le:message:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改消息通知对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="messageRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <el-input v-model="form.content" placeholder="请输入消息内容" />
        </el-form-item>
        <el-form-item label="消息类型" prop="messageType">
          <el-select v-model="form.messageType" placeholder="请选择消息类型">
            <el-option
              v-for="dict in message_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消息接收人编号" prop="receiverId">
          <el-input v-model="form.receiverId" placeholder="请输入消息接收人编号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in message_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Message">
import { listMessage, getMessage, delMessage, addMessage, updateMessage,yiduMessage,delMessageAll } from "@/api/le/message"
import { useUserStore } from '@/store/modules/user'

// 使用
const userStore = useUserStore()
console.log('用户信息：', userStore)
console.log('用户信息：', userStore.id)

const { proxy } = getCurrentInstance()
const { message_type, message_status } = proxy.useDict('message_type', 'message_status')

const messageList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangeCreateTime = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    createTime: null,
    messageType: null,
    status: null,
  },
  rules: {
    title: [
      { required: true, message: "标题不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询消息通知列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0]
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1]
  }
  queryParams.value.receiverId = userStore.id
  listMessage(queryParams.value).then(response => {
    messageList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function handleStatusChange(value) {
      // 直接调用原有的查询方法，使用已有的queryParams和接口
      queryParams.value.status = value;
      this.handleQuery();
    }

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    content: null,
    createTime: null,
    messageType: null,
    receiverId: null,
    status: null,
    extraField1: null,
    extraField2: null
  }
  proxy.resetForm("messageRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加消息通知"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getMessage(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改消息通知"
  })
}
/** 将消息标记为已读 */
function handleRead(row) {
  // 判断是单条操作还是批量操作
  if (row && row.id) {
    // 单条消息标记为已读
    getMessage(row.id).then(response => {
      const message = response.data;
      message.status = 1; // 将状态改为已读
      updateMessage(message).then(() => {
        proxy.$modal.msgSuccess("标记成功");
        getList();
      }).catch(() => {
        proxy.$modal.msgError("标记失败");
      });
    }).catch(() => {
      proxy.$modal.msgError("获取消息数据失败");
    });
  } else if (ids.value && ids.value.length > 0) {
    // 批量标记为已读 - 确保使用单个更新的方式
    // 这里循环处理每个选中的ID，使用updateMessage单独更新
    let successCount = 0;
    const totalCount = ids.value.length;
    
    ids.value.forEach(id => {
      getMessage(id).then(response => {
        const message = response.data;
        message.status = 1;
        return updateMessage(message);
      }).then(() => {
        successCount++;
        if (successCount === totalCount) {
          proxy.$modal.msgSuccess(`批量标记成功${successCount}/${totalCount}`);
          getList();
        }
      }).catch(() => {
        successCount++;
        if (successCount === totalCount) {
          proxy.$modal.msgSuccess(`批量标记成功${successCount}/${totalCount}`);
          getList();
        }
      });
    });
  } else {
    proxy.$modal.msgError("请选择要标记的消息");
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["messageRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMessage(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addMessage(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除消息通知编号为"' + _ids + '"的数据项？').then(function() {
    return delMessage(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}
// 全部删除按钮操作
function handleDeleteAll() {
  proxy.$modal.confirm('是否确认删除所有消息通知？').then(function() {
    return delMessageAll()
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}
// 全部已读
// 全部已读按钮操作
function handleYiduAll() {
  proxy.$modal.confirm('是否确认将所有消息通知标记为已读？').then(function() {
    return yiduMessage()
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("标记成功")
  }).catch(() => {})
}



/** 导出按钮操作 */
function handleExport() {
  proxy.download('le/message/export', {
    ...queryParams.value
  }, `message_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<style scoped>
.top-operation-bar {
  display: flex;
  justify-content: space-between; /* 实现两端分散对齐 */
  align-items: center; /* 垂直居中对齐 */
  margin-bottom: 10px; /* 与表格保持间距 */
}
.status-buttons {
  display: flex;
  gap: 0; /* 取消按钮组的间距 */
  background-color: #F2F2F2;
  width: 140px;
  flex-wrap: wrap;
  padding: 10px 0;
  border-radius: 10px;
  margin-bottom: 10px;
}
/* 按钮样式 */
:deep(.el-button) {
  padding: 6px 16px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

/* 默认按钮样式 */
.default-btn {
  background-color: #F2F2F2;
  color: #000000;
  border: 1px solid #F2F2F2;
}

.default-btn:hover {
  background-color: #e9ecef;
  color: #409eff;
  border-color: #c6e2ff;
}

/* 选中按钮样式 */
.active {
  background-color: white;
  color: #000000;
  border-color: white;
}

.active:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
.mb8 important{
  display: flex;
  justify-content: flex-end;
}
/* .operation-container {
  display: flex;
  justify-content: flex-end;
  width: 100%; 确保容器占满宽度
} */
</style>